#pragma once

#include <iostream>
#include <pthread.h>
#include <vector>
#include <queue>
#include "task.hpp"
#include "thread.hpp"

// struct threadinfo
// {
//     pthread_t td;
//     std::string name;
// };
const static int defaultnum = 5;
typedef void (*callback_t)();
template <class T>
class threadpool
{
    void Lock()
    {
        pthread_mutex_lock(&mutex_);
    }
    void Unlock()
    {
        pthread_mutex_unlock(&mutex_);
    }
    void Wakeup()
    {
        pthread_cond_signal(&cond_);
    }
    void ThreadSleep()
    {
        pthread_cond_wait(&cond_, &mutex_);
    }

public:
    threadpool(int num, callback_t cb) : threads_(num, Thread(cb))
    {

        pthread_mutex_init(&mutex_, nullptr);
        pthread_cond_init(&cond_, nullptr);
    }
    bool IsEmpty()
    {
        return tasks_.empty();
    }
    std::string GetThreadName(pthread_t td)
    {
        for (const auto &ti : threads_)
        {
            if (ti.tid_ == td)
                return ti.name_;
        }
        return "None";
    }
    static void Handlertask()
    {
        // std::string name = GetThreadName(pthread_self());
        // while (true)
        // {
        //     Lock();
        //     if (IsEmpty())
        //         ThreadSleep();
        //     T t = Pop();
        //     Unlock();
        //     t();
        //     std::cout << name << ", result:" << t.Getresult() << std::endl;
    }
    T Pop()
    {
        T t = tasks_.front();
        tasks_.pop();
        return t;
    }
    void Push(const T &t)
    {
        Lock();
        tasks_.push(t);
        Wakeup();
        Unlock();
    }
    void Start()
    {
        int num = threads_.size();
        for (int i = 0; i < num; i++)
        {
            threads_[i].cb_ = Handlertask;
        }
        for (int i = 0; i < num; i++)
        {
            threads_[i].Run();
        }
    }

    ~threadpool()
    {
        pthread_mutex_destroy(&mutex_);
        pthread_cond_destroy(&cond_);
    }

private:
    std::vector<Thread> threads_;
    std::queue<T> tasks_;
    pthread_mutex_t mutex_;
    pthread_cond_t cond_;
};